package com.example.springboot.config;

import com.example.springboot.bean.Pet;
import com.example.springboot.bean.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
//自定义MessageConverters  响应头 协议数据
@Configuration
public class 自定义响应头 implements HttpMessageConverter<User> {

    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return clazz.isAssignableFrom(User.class);
    }//能不能读

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return clazz.isAssignableFrom(User.class);
    }//能不能写


    /**
     * *服务器要统计所有 MessageConverter 都能写出哪些内容类型
     * application/x-long
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/x-long");
    }

    //写入写出  必须对应
    @Override
    public User read(Class<? extends User> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
        String[] tempArr = temp.split(";");
        return new User(tempArr[0], Integer.valueOf(tempArr[1]), new Pet(tempArr[2], Double.valueOf(tempArr[2])));
    }//自定义 写入

    @Override
    public void write(User user, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        String data = //user.toString();
                        user.getName() + ";" +
                        user.getAge() + ";" +
                        user.getPet().getName() + ";" +
                        user.getPet().getWeight();
        outputMessage.getBody().write(data.getBytes(StandardCharsets.UTF_8));
    }//自定义 写出
}
